import { CredentialMeta, GetCreditList, MessageItem } from "~/denokv/resume.ts";
import STDTable from "~/components/stdtable.tsx";
import { Handlers, PageProps } from "$fresh/server.ts";
import { DriveMeta } from "~/denokv/resume.ts";
interface MessageInfo {
  message: MessageItem["message"];
  email: MessageItem["email"];
  nickName: MessageItem["nickName"];
  subject: MessageItem["subject"];
  corporateName: CredentialMeta["corporateName"];
  driveId: DriveMeta["driveId"];
}
export const handler: Handlers<Partial<MessageInfo>[]> = {
  async GET(_, context) {
    const result = await GetCreditList();
    const infos = result.filter((i) => {
      const { drives } = i;
      if (!drives.length) return false;
      return drives.some((i) => i.messages?.length);
    });

    const tableData = infos.reduce<Partial<MessageInfo>[]>((pre, curr) => {
      const { drives, corporateName } = curr;
      const hasMessages = drives.filter((i) => i.messages?.length);
      const formatedMessages = hasMessages.reduce<Partial<MessageInfo>[]>(
        (pre, item) => {
          const { messages, driveId } = item;
          const formatedMessages = messages!.map<Partial<MessageInfo>>((j) => {
            return {
              message: j.message,
              email: j.email,
              nickName: j.nickName,
              subject: j.subject,
              corporateName,
              driveId,
            };
          });
          return pre.concat(formatedMessages);
        },
        [] as Partial<MessageInfo>[],
      );
      return pre.concat(formatedMessages);
    }, []);
    if (context.url.searchParams.has("di")) {
      const di = context.url.searchParams.get("di") as string;
      return context.render(tableData.filter((i) => i.driveId === di));
    }
    return context.render(tableData);
  },
};
export default (ctx: PageProps<Partial<MessageInfo>[]>) => {
  return (
    <STDTable<Partial<MessageInfo>>
      tableList={ctx.data}
      columns={[
        {
          title: "授权主体",
          header: "授权主体",
          key: "corporateName",
        },
        {
          title: "留言昵称",
          header: "留言昵称",
          key: "nickName",
        },
        {
          title: "主题",
          header: "主题",
          key: "subject",
        },
        {
          title: "联系邮箱",
          header: "联系邮箱",
          key: "email",
        },
        {
          title: "留言",
          header: "留言",
          key: "message",
        },
      ]}
    >
    </STDTable>
  );
};
